<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

Loader::loadThirdPart('saetv2.ex', 'class');

class Weibo
{
    protected $_oauth = null;
    protected $_client = null;
    protected $_config = null;
    
    public function __construct($config = null) {
        if(!$config) {
            $config = Loader::loadConfig(get_cookie('appweibo') == '1' ? 'appweibo' : 'weibo', 'member');
        }
        
        $this->_config = $config;
    }
    
    public function getOAuth() {
        if(!$this->_oauth) {
            $this->_oauth = new SaeTOAuthV2($this->_config['wb_akey'], $this->_config['wb_skey']);
        }
        
        return $this->_oauth;
    }
    
    public function getClient() {
        if(!$this->_client) {
            $this->_client = new SaeTClientV2($this->_config['wb_akey'], $this->_config['wb_skey'], $_SESSION['weibo']);
        }
        
        return $this->_client;
    }
    
    public function weibo_login() {
        $login_url = $this->getOAuth()->getAuthorizeURL($this->_config['callback']);
        header('Location:'.$login_url);
    }
    
    public function weibo_callback() {
        if(isset($_REQUEST['code'])) {
            $keys = array();
            $keys['code'] = $_REQUEST['code'];
            $keys['redirect_uri'] = $this->_config['callback'];
            try {
                $token = $this->getOAuth()->getAccessToken('code', $keys) ;
            } catch (OAuthException $e) {}
        }
        
        if($token) {
            $_SESSION['weibo'] = $token['access_token'];
            $_SESSION['weibo_uid'] = $token['uid'];
            set_cookie('weibo', '1');
            return $token;
        }
        
        return false;
    }
    
    public function applogin() {
        $data = $this->getOAuth()->parseSignedRequest($_REQUEST['signed_request']);
        if(empty($data['user_id'])) {
            return false;
        }
        
        $_SESSION['weibo'] = $data['oauth_token'];
        set_cookie('weibo', '1');
        set_cookie('appweibo', '1');

        return $data['user_id'];
    }
}